if (!window.myPlugin) {
    window.myPlugin = {};
}

// 右击菜单插件
myPlugin.contextmenu = (function () {
    let contextmenuDiv, // 右键菜单的容器
        menuItems = []; // 菜单项

    /**
     * 生成右击的菜单
     * @param {object} config 配置信息
     */
    function createContextmenu(config) {
        confgi = {
            location: {
                x: 0,
                y: 0
            },
            menuInfo: [],
            eventCallback: null,
            ...config
        }
        createMenuDiv(config.location);
        addMenuItem(config.menuInfo);
        rgEvent(config.eventCallback);
    }

    /**
     * 右键菜单的容器
     * @param {object} location 右击时鼠标的位置
     */
    function createMenuDiv(location) {
        if (!contextmenuDiv) {
            contextmenuDiv = document.createElement("div");
            contextmenuDiv.style.width = "150px";
            contextmenuDiv.style.borderRadius = "5px";
            contextmenuDiv.style.padding = "3px";
            contextmenuDiv.style.position = "fixed";
            contextmenuDiv.style.overflow = "hidden"
            contextmenuDiv.style.background = "rgba(75, 111, 255, 0.55)"
            contextmenuDiv.classList.add("contextmenuDiv");
            document.body.appendChild(contextmenuDiv);
        }
        contextmenuDiv.style.left = location.x - 5 + "px";
        contextmenuDiv.style.top = location.y - 18 + "px";
        contextmenuDiv.style.display = "block";
    }

    /**
     * 
     * @param {Array} info 菜单的包含的项目
     */
    function addMenuItem(info) {
        contextmenuDiv.innerHTML = "";
        info.forEach(name => {
            let menuItem = document.createElement("div");
            menuItem.style.height = "30px"
            menuItem.style.lineHeight = "30px"
            menuItem.style.borderRadius = "7px"
            menuItem.style.color = "#fff"
            menuItem.style.padding = "0 10px"
            menuItem.innerText = name;
            menuItem.classList.add("menuItem");
            contextmenuDiv.appendChild(menuItem);
            menuItems.push(menuItem);
        });
    }

    /**
     * 注册监听事件
     */
    function rgEvent(callback) {
        menuItems.forEach(item => {
            item.onmouseover = function (e) {
                e.target.style.background = "rgba(75, 111, 255, 0.8)";
                e.target.style.cursor = "pointer";
            }
            item.onmouseout = function (e) {
                this.style.background = "rgba(0, 0, 0, 0)";
            }
            item.onclick = function (e) {
                callback();
            }
        })
        contextmenuDiv.onmouseout = function (e) {
            if (e.target === this) {
                contextmenuDiv.style.display = "none";
            }
        }
    }

    return createContextmenu;
})();

// 上传文件时的表单
myPlugin.uploadForm = (function () {
    let maskDiv,
        middleDiv;

    // 返回的插件函数 
    function createForm(config) {
        initMaskDiv();
        initMiddleDiv(config.article.classify);
        rgEvent(config.callback);
    }

    // 初始化蒙层
    function initMaskDiv() {
        if (!maskDiv) {
            maskDiv = document.createElement("div");
            $(maskDiv).css("width", "100%");
            $(maskDiv).css("height", "100vh");
            $(maskDiv).css("position", "fixed");
            $(maskDiv).css("top", "0");
            $(maskDiv).css("left", "0");
            $(maskDiv).css("z-index", "9999");
            $(maskDiv).css("justify-content", "center");
            $(maskDiv).css("align-items", "center");
            $(maskDiv).addClass("uploadContainer");
            document.body.appendChild(maskDiv);
        }
        $(maskDiv).css("display", "flex");
    }

    // 初始化表单元素
    function initMiddleDiv(classify) {
        if (!middleDiv) {
            middleDiv = document.createElement("form");
            $(middleDiv).addClass("upload-form");
            $(middleDiv).css("display", "flex");
            // flex-direction: column;
            $(middleDiv).css("flex-direction", "column");
            // justify-content: center;
            // align-items: center;
            $(middleDiv).css("justify-content", "center");
            $(middleDiv).css("align-items", "center");
            middleDiv.innerHTML = `
                <div class = "form-item">
                    标题: <input type="text" name = "title" class = "txt">
                    <p></p>
                </div>
                <div  class = "form-item">
                    分类: <input type="text" name = "classify" class = "txt" value = '${classify}'>
                    <p></p>
                </div>
                <div  class = "form-item">
                    <input type="file" name = "content" id="mdFile">
                    <p></p>
                </div>
                <div  class = "form-item btn">
                    <button id="btnConfirm">确定</button>
                    <button id="btnCancel">取消</button>
                </div>
            `;
            maskDiv.appendChild(middleDiv);
        }
        const classifyIpt = middleDiv.querySelector(`input[name="classify"]`);
        classifyIpt.value = classify;
    }

    function rgEvent(callback) {
        // 点击蒙层关闭提交表单
        maskDiv.onclick = function (e) {
            if (e.target === this) {
                this.style.display = "none";
                clearMessage();
            }
        }

        // 表单提交事件
        middleDiv.addEventListener("submit", function (e) {
            e.preventDefault();
            const formData = new FormData(middleDiv);
            const data = Object.fromEntries(formData.entries());
            var input = document.getElementById('mdFile');
            var file = input.files[0]; // 获取文件引用

            // 创建FileReader对象
            var reader = new FileReader();

            // 当文件读取完成后触发的事件处理程序
            reader.onload = function (e) {
                var content = e.target.result;
                // console.log(content); // 在控制台输出文件内容
                data.content = content;
                if (callback) {
                    (function(...args){
                        callback(...args);
                    })(data)
                }
                // 这里可以添加你的代码，处理文件内容
            };

            // 以文本形式读取文件
            reader.readAsText(file);
            // upload() 上传文件，加工中
        })

        middleDiv.querySelector("#mdFile").addEventListener("change", function(e) {
            var file = this.files[0]; // 获取文件引用
            middleDiv.querySelector(`input[name="title"]`).value = file.name.match(/.*(?=\.md)/g)[0];
        })

        $(middleDiv).find("#btnCancel").click(function (e) {
            e.preventDefault();
            maskDiv.style.display = "none";
            clearMessage();
        });

        function clearMessage() {
            const title = middleDiv.querySelector(`input[name="title"]`);
            const classify = middleDiv.querySelector(`input[name="classify"]`);
            const file = middleDiv.querySelector(`input[name="content"]`);
            title.value = "";
            classify.value = "";
            file.value = "";
        }
    }

    return createForm;
})();